//
//  YPSearchViewController.m
//  Youpin
//
//  Created by xiaowuxiaowu on 2017/9/3.
//  Copyright © 2017年 xiaowuxiaowu. All rights reserved.
//

#import "YPSearchViewController.h"
#import "UISearchBar+TP.h"
#import "UIView+NotData.h"
#import "TPCityModel.h"
#import "TPHomeCell.h"
#import "TPHomeModel.h"
#import "TPProductDetailViewController.h"
@interface YPSearchViewController ()<UISearchBarDelegate>
@property (nonatomic,strong)NSMutableArray *searchHistory;
@property (nonatomic,strong)NSMutableArray *searchArray
;
@property (nonatomic,strong)UIImage *searchIconImage;
@property (nonatomic,assign)BOOL isSearching;
@property (nonatomic,strong)UIButton *clearButton;

@end

@implementation YPSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.searchArray = [NSMutableArray new];
    self.isSearching = YES;
    self.searchBar.hidden = NO;
    [self.tableView reloadData];
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.searchBar becomeFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.view endEditing:YES];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
-(void)getDataSearchText:(NSString *)text{
    
    [self.view endEditing:YES];
    [self.searchBar resignFirstResponder];
    [self.view tp_hideNotMsg];
    
    [[TPRequestClient sharedClient]getTemplateListCateId:0 cityName:@"" goods_salenum:@"" clinic_id:0 name:text recommend:false current:self.page size:kMaxRequestSize success:^(NSURLSessionDataTask *task, id responseObject, Responese *respone) {
       
        
        if(self.page == 1)
        [self.searchArray removeAllObjects];
        NSArray *array = [NSArray yy_modelArrayWithClass:[TPHomeModel class] json:respone.data[@"data"]];
        [self.searchArray addObjectsFromArray:array];
         self.isSearching= NO;
        [self refreshSccuess];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error, Responese *respone) {
        [self refreshFail];
    } nonetWork:^(NSURLSessionDataTask *task, NSError *error) {
        [self refreshFail];
    }];
    
    
}


-(UISearchBar *)searchBar{

    if(!_searchBar){
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, IPHONE_WIDTH*0.8, 44.0)];
        _searchBar.tintColor = [UIColor whiteColor];
        
        CGRect rect = CGRectMake(0.0f, 0.0f, IPHONE_WIDTH, 30.0f);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [TP_COLOR_245 CGColor]);
        CGContextFillRect(context, rect);
//        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [_searchBar setImage:ImageNamed(@"Search_icon") forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
//        [_searchBar setSearchFieldBackgroundImage:image forState:UIControlStateNormal];
        
        [_searchBar setPlaceholder: @"输入关键字进行搜索"];
        [_searchBar setBarTintColor:TP_COLOR_245];
        _searchBar.backgroundImage = ImageNamed(@"TextFliedclearImage");
        _searchBar.delegate = self;
        _searchBar.returnKeyType = UIReturnKeySearch;
        _searchBar.backgroundColor = [UIColor clearColor];
        self.navigationItem.titleView = _searchBar;
//        [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo([UIApplication sharedApplication].statusBarFrame.size.height);
//            make.height.mas_equalTo(44.0);
//            make.left.right.mas_equalTo(0.0);
//        }];
        _searchIconImage = [_searchBar imageForSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        
        if (@available(iOS 11.0, *)){
            self.navigationItem.hidesSearchBarWhenScrolling = false;
            [_searchBar.heightAnchor constraintEqualToConstant:44].active = true;
        }
    }

    return _searchBar;
}
-(UIButton *)clearButton{
    if(!_clearButton){
        
        _clearButton = [UIButton buttonWithFrame:CGRectMake(0, 0, self.view.width, 44.0) title:@"清除历史记录" font:fontSystemOfSize(14) color:TPBlack_999999];
        [_clearButton addTouchUpInsideTarget:self action:@selector(clcikClearButton:)];
    }
    return _clearButton;
}
#pragma mark---tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if(!self.isSearching){
        TPHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PYSearchViewController"];
        if(!cell){
            cell = [[TPHomeCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"PYSearchViewController"];
        }
//        cell.title = self.sid;
        cell.indexPath = indexPath;
        id model = self.dataSource[indexPath.row];
        cell.model = model;
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hzxCell"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"hzxCell"];
        cell.textLabel.font = fontSystemOfSize(15.0);
        cell.textLabel.textColor = TPBlack_999999;
        
    }
    cell.imageView.image = ImageNamed(@"Search_icon");
    cell.textLabel.text = self.dataSource[indexPath.row];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    if(self.isSearching){
        
        [self getDataSearchText:self.dataSource[indexPath.row]];
        
    }else{
        if(self.didBlock){
            self.didBlock(self.dataSource[indexPath.row]);
        }
        
        TPProductDetailViewController *detailVC = [TPProductDetailViewController new];
        detailVC.model = self.dataSource[indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [self.tableView tp_hideNotMsg];
    [searchBar setShowsCancelButton:YES animated:YES];
    self.isSearching = YES;
    return YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self leftBtnAction:nil];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
//    [searchBar setShowsCancelButton:NO animated:YES];
    self.isSearching = NO;
    if(searchBar.text.length > 0){
        [self addSearchText:searchBar.text];
        [self getDataSearchText:searchBar.text];
    }
    
}
-(void)setIsSearching:(BOOL)isSearching{
    _isSearching = isSearching;
    
    [self.tableView tp_hideNotMsg];
     [self.dataSource removeAllObjects];
    if(isSearching){
       
        [self.dataSource addObjectsFromArray:self.searchHistory];
        self.tableView.tableFooterView = self.clearButton;
    }else{
        [self.dataSource addObjectsFromArray:self.searchArray];
        self.tableView.tableFooterView = [UIView new];
    }
    if(self.dataSource.count == 0){
        self.tableView.tableFooterView = [UIView new];
        [self.tableView tp_addNotMsg:isSearching ? @"暂时没有搜索记录":@"搜索不到相关内容"];
        
    }
    
    [self.tableView reloadData];
}


-(NSMutableArray *)searchHistory{
    if(!_searchHistory){
        NSArray *array = [[NSUserDefaults standardUserDefaults]objectForKey:@"searchHistory"];
        
              _searchHistory = [NSMutableArray new];
        if(array.count > 0)
           [_searchHistory addObjectsFromArray:array];
    }
    return _searchHistory;
}
-(void)addSearchText:(NSString *)text{
  
    if(self.searchHistory.count == 0){
        [self.searchHistory addObject:text];
    }else{
        [self.searchHistory insertObject:text atIndex:0];
    }
    [[NSUserDefaults standardUserDefaults]setObject:self.searchHistory forKey:@"searchHistory"];
}
-(void)clcikClearButton:(UIButton*)sender{
 [self.searchHistory removeAllObjects];
    self.isSearching = YES;
     [[NSUserDefaults standardUserDefaults]setObject:self.searchHistory forKey:@"searchHistory"];
}


@end
